import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gamma
import pickle
import matplotlib.patches as patches


def matern_cluster_process(
    center, radius, num_clusters, lambda_p, mean_cluster_size, gamma_shape
):
    """
    模拟Matern簇过程

    :param center: 圆形区域的中心坐标 (x0, y0)
    :param radius: 圆形区域的半径
    :param num_clusters: 母点（簇中心）的数量
    :param lambda_p: 母点过程的强度
    :param mean_cluster_size: 平均簇大小
    :param gamma_shape: 用于生成簇半径的伽马分布的形状参数
    :return: 模拟得到的所有点的坐标数组，簇中心点的x坐标数组，簇中心点的y坐标数组，以及每个点是否为正方形点的标记数组
    """
    # 生成母点（簇中心）的坐标
    parent_points_x = np.random.uniform(
        center[0] - radius, center[0] + radius, num_clusters
    )
    parent_points_y = np.random.uniform(
        center[1] - radius, center[1] + radius, num_clusters
    )

    all_points = []
    square_markers = []  # 存储每个点是否为正方形点的标记

    for i in range(num_clusters):
        # 生成簇半径
        cluster_radius = gamma.rvs(gamma_shape)

        # 生成簇内点的数量，假设服从泊松分布
        num_points_in_cluster = np.random.poisson(mean_cluster_size)

        # 生成簇内点的坐标
        points_in_cluster_x = np.random.uniform(
            parent_points_x[i] - cluster_radius,
            parent_points_x[i] + cluster_radius,
            num_points_in_cluster,
        )
        points_in_cluster_y = np.random.uniform(
            parent_points_y[i] - cluster_radius,
            parent_points_y[i] + cluster_radius,
            num_points_in_cluster,
        )

        # 筛选出在圆形区域内的点
        valid_indices = np.where(
            (points_in_cluster_x - center[0]) ** 2
            + (points_in_cluster_y - center[1]) ** 2
            <= radius**2
        )
        valid_points_x = points_in_cluster_x[valid_indices]
        valid_points_y = points_in_cluster_y[valid_indices]

        # 以 0.2 的概率标记为正方形点，标记为 1 表示是正方形点，0 表示不是
        is_square = (np.random.rand(len(valid_points_x)) < 0.2).astype(int)
        square_markers.extend(is_square)
        all_points.extend(
            [(x, y) for x, y, square in zip(valid_points_x, valid_points_y, is_square)]
        )

    return (
        np.array(all_points),
        parent_points_x,
        parent_points_y,
        np.array(square_markers),
    )


# 设置参数
center = (0, 0)  # 圆形区域中心坐标
radius = 20  # 圆形区域半径
num_clusters = 20  # 母点（簇中心）数量
lambda_p = 0.5  # 母点过程的强度
mean_cluster_size = 8  # 平均簇大小
gamma_shape = 2  # 用于生成簇半径的伽马分布的形状参数

# 模拟Matern簇过程
points, parent_points_x, parent_points_y, square_markers = matern_cluster_process(
    center, radius, num_clusters, lambda_p, mean_cluster_size, gamma_shape
)


# 将生成的点数据保存到文件中（使用pickle模块）
with open("matern_cluster_square_data.pkl", "wb") as f:
    pickle.dump((points, parent_points_x, parent_points_y, square_markers), f)


# 创建一个包含两个子图的窗口
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))

# 获取离坐标原点最近的两个点的距离，以此距离作为半径画圆（修改后的关键逻辑）
distances = np.sqrt((points[:, 0] - center[0]) ** 2 + (points[:, 1] - center[1]) ** 2)
sorted_indices = np.argsort(distances)
radius_w = distances[
    sorted_indices[1]
]  # 取第二个最近的距离作为半径（索引从0开始，所以取1）
circle1 = plt.Circle(center, radius_w, fill=False, color="black")
ax1.add_patch(circle1)
circle2 = plt.Circle(center, radius_w, fill=False, color="black")
ax2.add_patch(circle2)

# 找出圆内的点
in_circle = (points[:, 0] - center[0]) ** 2 + (
    points[:, 1] - center[1]
) ** 2 <= radius_w**2

# 分离标记为正方形的点和非正方形的点
square_points = points[square_markers == 1]
non_square_points = points[square_markers == 0]

# 在第一个子图中绘制模拟Matern簇过程的图形
ax1.scatter(
    non_square_points[:, 0],
    non_square_points[:, 1],
    label="Non-Square Points",
    c="blue",
)
ax1.scatter(
    square_points[:, 0],
    square_points[:, 1],
    label="Square Points",
    c="red",
    marker="s",
)
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(num_clusters)]
)
ax1.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
ax1.set_xlim(center[0] - radius, center[0] + radius)
ax1.set_ylim(center[1] - radius, center[1] + radius)
ax1.set_aspect("equal", adjustable="box")
ax1.set_title("Matern Cluster Process")
ax1.set_xlabel("X-axis")
ax1.set_ylabel("Y-axis")
ax1.legend()


# 为标记为正方形的点绘制正方形
for x, y in square_points:
    rect = patches.Rectangle(
        (x - 0.5, y - 0.5),
        1,
        1,
        linewidth=1,
        edgecolor="red",
        facecolor="none",
    )
    ax1.add_patch(rect)


# 剔除圆内的点，获取用于聚类的点
points_for_clustering = points[~in_circle]


# 使用DBSCAN进行聚类
# 这里先注释掉 DBSCAN 部分，因为你要求在 DBSCAN 之前存储文件
# dbscan = DBSCAN(eps=2.5, min_samples=3)  # 这里的参数可根据实际情况调整
# clusters = dbscan.fit_predict(points_for_clustering)


# 提取不同簇的点和噪声点，注意要根据points_for_clustering的索引对应回原points的索引来处理
# unique_clusters = np.unique(clusters)


# 标注willie
ax1.scatter(0, 0, marker="+", s=100, c="r", label="Willie")
ax2.scatter(0, 0, marker="+", s=100, c="r", label="Willie")


# 将圆内的点变红
ax1.scatter(points[in_circle, 0], points[in_circle, 1], c="red")
ax2.scatter(points[in_circle, 0], points[in_circle, 1], c="red")


# 绘制第二个子图
ax2.scatter(
    non_square_points[:, 0],
    non_square_points[:, 1],
    label="Non-Square Points",
    c="blue",
)
ax2.scatter(
    square_points[:, 0],
    square_points[:, 1],
    label="Square Points",
    c="red",
    marker="s",
)
ax2.set_xlim(center[0] - radius, center[0] + radius)
ax2.set_ylim(center[1] - radius, center[1] + radius)
ax2.set_aspect("equal", adjustable="box")
ax2.set_title("Matern Cluster Process")
ax2.set_xlabel("X-axis")
ax2.set_ylabel("Y-axis")
ax2.legend()


# 为标记为正方形的点绘制正方形
for x, y in square_points:
    rect = patches.Rectangle(
        (x - 0.5, y - 0.5),
        1,
        1,
        linewidth=1,
        edgecolor="red",
        facecolor="none",
    )
    ax2.add_patch(rect)


plt.show()
